package com.lyf.security.login.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lyf.security.login.ResponseResult;
import com.lyf.security.login.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;

/**
 * @AUTHOR LYF
 * @DATE 2022/1/21
 * @VERSION 1.0
 * @DESC 登录控制器
 * 每次生成的token一致有无影响（Redis设置了时效性）
 * 还是动态生成较好》》，防止返回被拦截包，获取token信息
 */
@RestController
public class LoginController {
    @Autowired
    LoginService loginService;

    @RequestMapping("/userLogin")// 用户名,密码登录
    ResponseResult<String> userLogin(@RequestBody JSONObject req){
        System.out.println("进入LoginController");
        ResponseResult<String> rs = new ResponseResult<>();
        String username = req.getString("username");
        String password = req.getString("password");
        rs = new ResponseResult<>("0","登录失败","");
        if(loginService.validate(username,password)){
            // 加token,存缓存(存放permission列表; 将账户进行token; 将权限表
            String token = DigestUtils.md5DigestAsHex(username.getBytes(StandardCharsets.UTF_8));
            // 将token按key存入Redis,value 内容为 该用户的Id(username当唯一属性,也可再次查询，
            // 开销查询时间..., 再通过Id拿权限列表（采用redis的list） ;若非得再查询ID，则在validate处进行...
            // 避免多次查询
            loginService.saveToken(token,username);
            rs = new ResponseResult<>("1","登录成功",token);
        }
        return rs;
    }

}
